package com.clw.service.impl;

import com.clw.dataobject.SupplierInfo;
import com.clw.repository.SupplierInfoRepository;
import com.clw.service.SupplierInfoService;
import com.clw.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018-03-07.
 */
@Service
public class SupplierInfoServiceImpl implements SupplierInfoService {

    @Autowired
    private SupplierInfoRepository repository;
    @Override
    public List<SupplierInfo> findAll() {
        return repository.findAll();
    }

    @Override
    public SupplierInfo save(SupplierInfo supplierInfo) {
        return repository.save(supplierInfo);
    }

    @Override
    public void del(SupplierInfo supplierInfo) {
        repository.delete(supplierInfo);
    }


    @Override
    public SupplierInfo findOne(Integer id) {
        return repository.findOne(id);
    }

    @Override
    public Page<SupplierInfo> findAll(String name, String phone, String status, Pageable pageable) {
        return repository.findAll(getSpecification(name,phone,status),pageable);
    }

    @Override
    public Long getSize(String name, String phone, String status) {
        return repository.count(getSpecification(name,phone,status));
    }

    @Override
    public List<SupplierInfo> findValid(Integer status) {
        return repository.findAllByStatus(status);
    }

    private Specification<SupplierInfo> getSpecification(String name, String phone, String status){
        return new Specification<SupplierInfo>() {
            @Override
            public Predicate toPredicate(Root<SupplierInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates=new ArrayList<>();
                if (StringUtils.isNotEmpty(name)){
                    predicates.add(criteriaBuilder.like(root.get("name"),"%"+name+"%"));
                }
                if (StringUtils.isNotEmpty(phone)){
                    predicates.add(criteriaBuilder.like(root.get("phone"),"%"+phone+"%"));
                }
                if (StringUtils.isNotEmpty(status)&&!"-2".equals(status)){
                    predicates.add(criteriaBuilder.equal(root.get("status"),Integer.valueOf(status)));
                }
                return criteriaQuery.where(predicates.toArray
                        (new Predicate[predicates.size()])).getRestriction();
            }
        };
    }
}
